<template>
  <div class="login-container">
    <div class="auth-form-wrapper">
      <div class="page-title">
        <h1>欢迎使用优驾租管一体化平台</h1>
      </div>
      <!-- 注册/登录表单 -->
      <div class="auth-form" :class="{ 'register-mode': isRegister }">
        <!-- 注册表单 -->
        <el-form ref="form" style="max-width: 600px" label-width="auto"  autocomplete="on" v-if="isRegister" :model="registerData" :rules="rules">
          <h1>注册</h1>
          <!--         选择角色-->
          <el-form-item label="选择角色" >
            <el-select  placeholder="请选择" v-model="registerData.role">
              <el-option label="商家" :value="'商家'" />
              <el-option label="用户" :value="'用户'" />
            </el-select>
          </el-form-item>
<!--       用户注册-->
          <template v-if="registerData.role === '用户'">
            <el-form-item prop="username" label="登录用户名">
              <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
              <el-input :prefix-icon="Phone" placeholder="请输入手机号" v-model="registerData.phone"></el-input>
            </el-form-item>
            <el-form-item prop="realName" label="真实姓名">
              <el-input :prefix-icon="User" placeholder="请输入真实姓名" v-model="registerData.realName"></el-input>
            </el-form-item>
            <el-form-item prop="idCard" label="身份证号">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入身份证号" v-model="registerData.idCard"></el-input>
            </el-form-item>
            <el-form-item prop="driverLicenseEncrypted" label="驾驶证号">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入驾驶证号" v-model="registerData.driverLicenseEncrypted"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="  密码">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
            </el-form-item>
            <el-form-item prop="rePassword" label="确认密码">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                        v-model="registerData.rePassword"></el-input>
            </el-form-item>
            <el-form-item prop="avatarUrl" label="头像">
              <el-upload
                  class="avatar-uploader"
                  action="/api/file/upload.do"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  v-model="registerData.avatarUrl"
              >
                <el-image v-if="imageUrl" :src="imageUrl" class="avatar"></el-image>
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </template>
<!--       商家注册-->
          <template v-if="registerData.role === '商家'" >
            <el-form-item prop="username" label="登录名">
              <el-input :prefix-icon="User" placeholder="请输入登录名" v-model="registerData.username"></el-input>
            </el-form-item>
            <el-form-item prop="merchantName" label="商家名称">
              <el-input :prefix-icon="User" placeholder="请输入商家名称" v-model="registerData.merchantName"></el-input>
            </el-form-item>
            <el-form-item prop="contactPerson" label="联系人">
              <el-input :prefix-icon="User" placeholder="请输入联系人" v-model="registerData.contactPerson"></el-input>
            </el-form-item>
            <el-form-item prop="contactPhone" label="联系电话">
              <el-input :prefix-icon="Phone" placeholder="请输入联系电话" v-model="registerData.contactPhone"></el-input>
            </el-form-item>
            <el-form-item prop="address" label="商家地址">
              <el-input :prefix-icon="Location" placeholder="请输入商家地址" v-model="registerData.address"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="  密码">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
            </el-form-item>
            <el-form-item prop="rePassword" label="确认密码">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                        v-model="registerData.rePassword"></el-input>
            </el-form-item>
          </template>
          <template v-if="registerData.role === '商家'">
            <!-- 营业执照和商家logo水平排列 -->
            <el-row :gutter="60"> <!-- 间距20px -->
              <!-- 营业执照 -->
              <el-col :span="2">

              </el-col>
              <el-col :span="10">
                <el-form-item>
                  <el-upload
                      class="avatar-uploader"
                      action="/api/file/upload.do"
                      :show-file-list="false"
                      :on-success="(res, file) => handleUploadSuccess(res, file, 'businessLicense')"
                      :before-upload="beforeAvatarUpload"
                  >
                    <el-image
                        v-if="imageUrl"
                        :src="imageUrl"
                        class="avatar"
                        :preview-src-list="[imageUrl]"
                        fit="cover"
                    />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>

                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item>
                  <el-upload
                      class="avatar-uploader"
                      action="/api/file/upload.do"
                      :show-file-list="false"
                      :on-success="(res, file) => handleUploadSuccess(res, file, 'logoUrl')"
                      :before-upload="beforeAvatarUpload"
                  >
                    <el-image
                        v-if="imageUrl2"
                        :src="imageUrl2"
                        class="avatar"
                        :preview-src-list="[imageUrl2]"
                        fit="cover"
                    />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80">
              <el-col :span="3"></el-col>
              <el-col :span="9">
                <div class="upload-label">营业执照</div> <!-- 标签移至下方 -->
              </el-col>
              <el-col :span="11">
                  <div class="upload-label">商家logo</div> <!-- 标签移至下方 -->
              </el-col>
            </el-row>
          </template>
          <!-- 返回-注册按钮 -->
          <el-form-item class="flex-container"> <!-- 父容器添加 Flex 样式 -->
            <el-button class="button" type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
              ← 返回
            </el-button>
            <el-button class="button" type="primary" auto-insert-space @click="register" :disabled="!registerData.role">
              {{ registerData.role==="用户"?"注册":"注册申请" }}</el-button>
          </el-form-item>

        </el-form>

        <!-- 登录表单 -->
        <el-form ref="form" style="max-width: 600px" label-width="auto" v-else :model="registerData" :rules="rules" >
          <el-form-item>
            <h1>登录</h1>
          </el-form-item>
          <el-form-item prop="username" label="用户名">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username" class="el-input__inner"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="  密码">
            <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                      v-model="registerData.password" class="el-input__inner"></el-input>
          </el-form-item>
          <el-form-item label="选择角色" >
            <el-select  placeholder="请选择" v-model="registerData.role">
              <el-option label="商家" :value="'商家'" />
              <el-option label="用户" :value="'用户'" />
              <el-option label="管理员" :value="'管理员'" />
            </el-select>
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>
          </el-form-item>
          <!-- 登录按钮 -->
          <el-form-item>
            <el-button class="login-button" type="primary" auto-insert-space @click="login">
              登录
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()">
              注册 →
            </el-link>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>

<style lang="scss" scoped>
/* 登录页面整体容器 */
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: url('@/assets/mainCar.png') no-repeat center center / cover;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;

  /* 添加半透明遮罩层 */
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    z-index: -1;
  }
}
/* 表单包装器 */
.auth-form-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 450px; /* 比表单略宽，给标题留出空间 */
}
/* 页面标题 */
.page-title {
  margin-bottom: 30px;
  text-align: center;

  h1 {
    color: white;
    font-size: 28px;
    font-weight: 600;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
}

/* 认证表单容器 */
.auth-form {
  background-color: rgba(255, 255, 255, 0.5); /* 设置为90%不透明度的白色 */
  border-radius: 12px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  width: 90%;
  max-width: 400px;
  padding: 40px;
  margin: 20px;
  transition: all 0.6s ease-in-out;

  /* 表单标题样式 */
  h1 {
    font-weight: bold;
    margin: 0 0 20px 0;
    text-align: center;
    color: #333;
  }
  .login-button {
    width: 100%;
    margin-top: 15px;
    font-size: 16px;
    height: 44px;
    border-radius: 6px;
  }


  /* 链接样式 */
  .flex {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;

    a {
      cursor: pointer;
      color: #409EFF;

      &:hover {
        text-decoration: underline;
      }
    }
  }
  .el-form-item {
    label {
      text-align: left; /* 确保label右对齐 */
      padding-right: 10px; /* 增加label与输入框的间距 */
    }

    .uniform-input {
      width: 100%; /* 输入框占满父容器宽度 */

      /* 修正ElInput前缀图标与输入框的间距 */
      &::before {
        content: '';
        display: table;
        clear: both;
      }

      .el-input__inner {
        width: calc(100% - 36px); /* 减去前缀图标的宽度 */
        float: right; /* 输入框右浮动 */
      }

      .el-input__prefix {
        float: left; /* 前缀图标左浮动 */
        margin-right: 10px; /* 图标与输入框的间距 */
      }
    }

    .el-select {
      .uniform-input {
        width: 100%;

        .el-input__inner {
          width: 100%;
          float: none;
        }

        .el-input__prefix {
          float: none;
        }
      }
    }
  }
}

/* 适配小屏幕设备 */
@media (max-width: 480px) {
  .auth-form {
    padding: 30px 20px;
    max-width: 90%;
  }
}
</style>
<!-- 注册表单按钮样式-->
<style scoped>
.flex-container {
  display: flex;
  justify-content: space-between; /* 关键：强制左右分布 */
  align-items: center;
  width: 100%;
  margin-top: 15px;
}

/* 按钮样式 */
.flex-container .el-button {
  width: 47%; /* 两个按钮各占40%宽度，剩余20%作为间距 */
  height: 44px;
  font-size: 16px;
  border-radius: 6px;
}
</style>
<!--图片样式-->
<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  width: 100px;  /* 容器宽度 = 头像宽度 */
  height: 100px; /* 容器高度 = 头像高度 */
  background-color: #ffffff;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  transition: var(--el-transition-duration-fast);
}
/* 缩小上传图标尺寸，与容器匹配 */
.el-icon.avatar-uploader-icon {
  font-size: 20px; /* 图标缩小 */
  color: #8c939d;
  width: 100px;    /* 图标容器宽度 = 上传框宽度 */
  height: 100px;   /* 图标容器高度 = 上传框高度 */
  line-height: 100px; /* 图标垂直居中 */
  text-align: center;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>

<script setup>
import { ref } from 'vue'
import { Lock, User,Phone,Hide ,Location,Avatar,Picture} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { userInsert, userLogin} from '@/api/user'
import { useUserInfoStore } from '@/stores/userInfo'
import { useMerchantInfoStore } from '@/stores/merchantInfo'
import { Plus } from '@element-plus/icons-vue'
// 状态管理
const isRegister = ref(false)
// 数据模型
const registerData = ref({
  username: '',//登录名
  password: '',
  rePassword: '',
  realName: '',
  phone: '',
  idCard: '',
  driverLicenseEncrypted: '',//驾驶证号
  avatarUrl: '',
  role: '',
  //商家
  merchantName:'',//商家名称
  contactPerson:'',
  contactPhone:'',
  address:'',
  businessLicense:'',//营业执照
  logoUrl:'',//商家logo

})
// 自定义校验 - 判断两次输入密码是否一致
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('两次密码不一样'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 16, message: '用户名长度为2-16位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度为3-20位', trigger: 'blur' }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: checkRePassword, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 3, max: 11, message: '手机号格式不正确', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '真实姓名长度为2-10位', trigger: 'blur' }
  ],
  merchantName: [
    { required: true, message: '请输入商家名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商家名称长度为2-50位', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { min: 2, max: 20, message: '联系人长度为2-20位', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { min: 2, max: 11, message: '联系电话格式不正确', trigger: 'blur' }
  ]
}
const router = useRouter() // 路由跳转
const form = ref(null)
// 注册方法 (待实现)
const register = () => {
  form.value.validate((valid) => {
    if (valid) {
      const obj = {
          role: registerData.value.role,
          username: registerData.value.username,
          password: registerData.value.password,
          phone: registerData.value.phone,
          realName: registerData.value.realName,
          idCard: registerData.value.idCard,
          avatarUrl: registerData.value.avatarUrl,
        //商家
          driverLicenseEncrypted: registerData.value.driverLicenseEncrypted,
          merchantName: registerData.value.merchantName,
          contactPerson: registerData.value.contactPerson,
          contactPhone: registerData.value.contactPhone,
          businessLicense: registerData.value.businessLicense,
          logoUrl: registerData.value.logoUrl,
          address: registerData.value.address,
      }
      console.log(obj)
      userInsert(obj).then(res => {
        console.log(res)
        if (res.success) {
          ElMessage.success(res.message || '注册成功')
          isRegister.value = false
        }
        else {
          ElMessage.error(res.message || '注册失败')
        }
      })
    }
  })
}
// 登录方法
const login = () => {
  form.value.validate((valid) => {
    if (valid) {
      const obj = {
        params: {
          username: registerData.value.username,
          password: registerData.value.password,
          role: registerData.value.role,
        }
      }
      userLogin(obj).then(res => {
        if (res.success) {
          useUserInfoStore().setUserInfo(res.data)
          ElMessage.success(res.message || '登录成功')
          // 根据角色跳转路由

          if (obj.params.role === '商家') {
            useMerchantInfoStore().setMerchantInfo({
              id: res.data.id,               // 关键字段
              merchantName: res.data.merchantName || '',
              contactPerson: res.data.contactPerson || '',
              contactPhone: res.data.contactPhone || '',
              address: res.data.address || '',
              businessLicense: res.data.businessLicense || '',
              description:res.data.description||'',
              logoUrl: res.data.logoUrl || ''
            })
            localStorage.setItem('merchantId', res.data.id) // 可选：再存一份
            router.push({ path: '/carList' })
          }

          if (obj.params.role === '管理员'){router.push({ path: '/admin' })}
          else if(obj.params.role === '用户'){router.push({ path: '/user/CarBrowse' })}
          else if (obj.params.role === '商家'){router.push({ path: '/carList' })}
        }
        else {
          ElMessage.error(res.message || '登录失败')
        }
      }).catch(error => {
        ElMessage.error('登录失败，请稍后再试')
        console.error('登录错误:', error)
      })
    }
  })
}
// 清除表单数据
const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    rePassword: '',
    role: '',
    phone: '',
    email: '',
    address: '',
    gender: ''
  }
}
const imageUrl = ref('')
const imageUrl2 = ref('')
// 图片上传成功回调
const handleAvatarSuccess = (response, uploadFile) => {
  // 1. 回显图片（使用上传的原始文件临时路径）
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  // 2. 将后端返回的图片文件名存入表单数据（假设response.data是文件名）
  registerData.value.avatarUrl = response.message; // 后端需返回图片存储的文件名
};
// 处理商家营业执照和logo上传成功（区分类型）
const handleUploadSuccess = (response, file, fieldType) => {
  const localUrl = URL.createObjectURL(file.raw);
  // 根据上传类型，将服务器路径存入对应的表单字段
  if (fieldType === 'businessLicense') {
    imageUrl.value = localUrl;
    registerData.value.businessLicense = response.message; // 营业执照路径
  } else if (fieldType === 'logoUrl') {
    imageUrl2.value = localUrl;
    registerData.value.logoUrl = response.message; // 商家logo路径
  }
};
// 图片上传前校验（支持jpg、png）
const beforeAvatarUpload = (rawFile) => {
  const isJpgOrPng = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG或PNG格式的图片!');
    return false;
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
};
</script>